package com.aoxin.controller.system;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.aoxin.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aoxin.model.course.SlfChildren;
import com.aoxin.model.opm.SlfEmployee;
import com.aoxin.model.opm.SlfUser;
import com.aoxin.service.inter.course.webCourse.ChildrenService;
import com.aoxin.service.inter.opm.EmployeeService;
import com.aoxin.service.inter.opm.UserService;
import com.aoxin.service.inter.system.CommonService;
import com.aoxin.util.enumerate.OperateType;
import com.aoxin.util.enumerate.UserType;
import com.aoxin.util.log.LogInfo;

/**
 * 登录Controller
 *
 * @author Melody
 * @date 2018年3月27日 下午3:36:50
 */
@Controller
@RequestMapping("/web")
@ResponseBody
    public class LoginController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private UserService userService;

    @Autowired
    private ChildrenService childrenService;

    //管理端登陆
    @RequestMapping("/manageLogin")
    public AjaxRes initialise(@RequestParam("loginName") String loginName, @RequestParam("password") String password, HttpServletRequest request, AjaxRes ajaxRes) {
        try {
            SlfEmployee operator = this.employeeService.getByLoginNameAndPassword(loginName, password);
            if (null != operator) {
                String token = UUID.getUUID();
                operator.setToken(token);
                HttpSession session = request.getSession();
                String oldtoken = (String) RedisUtil.get(operator.getLoginAccount() + operator.getEmployeeId());
                if (null != oldtoken) {
                    RedisUtil.del(oldtoken);
                    RedisUtil.del(operator.getLoginAccount() + operator.getEmployeeId());
                }
                session.setAttribute("employeeSession", operator.getLoginAccount() + operator.getEmployeeId());
                RedisUtil.set(operator.getLoginAccount() + operator.getEmployeeId(), token);
                RedisUtil.set(token, operator);
                ajaxRes.setSucceed(operator, ErrorUtil.LOGIN_SUCCESS);
            } else {
                ajaxRes.setFailMsg(ErrorUtil.LOGIN_FAILURE);
            }
        } catch (Exception e) {
            ajaxRes.setFailMsg(e.getMessage());
        }
        return ajaxRes;
    }

    //管理端注销
    @RequestMapping("/manageLogout")
    @LogInfo(content = "员工注销登录", operateType = OperateType.LOGOUT)
    public AjaxRes manageLogout(HttpServletRequest request, AjaxRes ajaxRes) {
        try {
            String employeeSession = (String) request.getSession().getAttribute("employeeSession");
            if (null != employeeSession) {
                RedisUtil.del(employeeSession);
                String token = (String) RedisUtil.get(employeeSession);
                if (null != token) {
                    RedisUtil.del(token);
                }
            }
            ajaxRes.setFailMsg(ErrorUtil.LOGOUT_SUCCESS);
        } catch (Exception e) {
            ajaxRes.setFailMsg(e.getMessage());
        }
        return ajaxRes;
    }

    //用户端用户名密码登陆
    @RequestMapping("/userLogin")
    public AjaxRes userLogin(@RequestParam("loginName") String loginName, @RequestParam("password") String password, HttpServletRequest request, AjaxRes ajaxRes) {
        try {
            SlfUser user = this.userService.getByLoginNameAndPassword(loginName, password);
            if (null != user) {
                String token = UUID.getUUID();
                user.setToken(token);
                HttpSession session = request.getSession();
                String oldtoken = (String) RedisUtil.get(user.getPhone() + user.getUserId());
                if (null != oldtoken) {
                    RedisUtil.del(oldtoken);
                    RedisUtil.del(user.getPhone() + user.getUserId());
                }
                session.setAttribute("userSession", user.getPhone() + user.getUserId());
                RedisUtil.set(user.getPhone() + user.getUserId(), token);
                RedisUtil.set(token, user);

                List<SlfChildren> childrens = this.childrenService.getChildrenInfo(user.getUserId());
                SlfChildren oldslfChildren = (SlfChildren) RedisUtil.get(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
                if (null != oldslfChildren) {
                    RedisUtil.del(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
                }

                // 默认选中最新添加的孩子
                RedisUtil.set(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE, childrens.get(0));
                //展示对应账号下的默认孩子信息

                ajaxRes.setSucceed(user, ErrorUtil.LOGIN_SUCCESS);
            } else {
                ajaxRes.setFailMsg(ErrorUtil.LOGIN_FAILURE);
            }
        } catch (Exception e) {
            ajaxRes.setFailMsg(e.getMessage());
        }
        return ajaxRes;
    }

    //用户验证码登陆
    @RequestMapping("/userIdentifyCodeLogin")
    public AjaxRes userIdentifyCodeLogin(@RequestParam("loginName") String loginName, @RequestParam("password") String password, HttpServletRequest request, HttpServletResponse response, AjaxRes ajaxRes) {

        try {
			String identifyCode = (String) RedisUtil.get(loginName + CommonService.PHONE_IDENTIFY_CODE);
			if (null != identifyCode) {
				if (identifyCode.equals(password)) {
					SlfUser user = this.userService.getByLoginNameAndPassword(loginName, null);
					if (null != user) {
						String token = UUID.getUUID();
						user.setToken(token);
						HttpSession session = request.getSession();
						String oldtoken = (String) RedisUtil.get(user.getPhone() + user.getUserId());
						if (null != oldtoken) {
							RedisUtil.del(oldtoken);
							RedisUtil.del(user.getPhone() + user.getUserId());
						}
						session.setAttribute("userSession", user);
						RedisUtil.set(user.getPhone() + user.getUserId(), token);
						RedisUtil.set(token, user);
						ajaxRes.setSucceed(user, ErrorUtil.LOGIN_SUCCESS);
						RedisUtil.del(loginName + CommonService.PHONE_IDENTIFY_CODE);

						// 默认选中最新添加的孩子
						List<SlfChildren> childrens = this.childrenService.getChildrenInfo(user.getUserId());
						if("1".equals(RedisUtil.get(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE))){
							//存在的异常情况返回类型为integer  清除缓存
							RedisUtil.del(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
						}
						SlfChildren oldslfChildren = (SlfChildren) RedisUtil.get(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
						if (null != oldslfChildren) {
							RedisUtil.del(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE);
						}
						//判断该用户下是否有孩子
						if(childrens.size() > 0) {
							RedisUtil.set(user.getPhone() + user.getUserId() + ChildrenService.REDIS_CHILDREN_CODE, childrens.get(0));
						}
                        CookieUtil.saveCookie("slfCookie", user.getUserId().toString());
					} else {
						ajaxRes.setFailMsg(ErrorUtil.LOGIN_ACCOUNT_NON_EXISTENT);
					}
				} else {
					ajaxRes.setFailMsg(ErrorUtil.IDENTIFY_CODE_ERROR);
				}
			} else {
				ajaxRes.setFailMsg(ErrorUtil.LOGIN_IDENTIFY_CODE_ABATE);
			}
		} catch (Exception e) {
			ajaxRes.setFailMsg(e.getMessage());
		}
        return ajaxRes;
    }

    //用户注销
    @RequestMapping("/userLogout")
    @LogInfo(content = "用户注销登录", operateType = OperateType.LOGOUT, userType = UserType.USER)
    public AjaxRes userLogout(HttpServletRequest request, HttpServletResponse response,AjaxRes ajaxRes) {
        try {
            SlfUser  user= (SlfUser) request.getSession().getAttribute("userSession");
            
            if (null != user) {
            	System.out.println("======================="+user.toString());
                request.getSession().removeAttribute("userSession");
                RedisUtil.del(user.getPhone() + user.getUserId());
                removeCookie(request,response);
                String token = (String) RedisUtil.get(user.getPhone() + user.getUserId());
                if (null != token) {
                    RedisUtil.del(token);
                }
            }
            ajaxRes.setFailMsg(ErrorUtil.LOGOUT_SUCCESS);
        } catch (Exception e) {
            ajaxRes.setFailMsg(e.getMessage());
        }
        return ajaxRes;
    }

    /**
     * 移除cookie
     * @param request
     * @param response
     */
    private void removeCookie(HttpServletRequest request,HttpServletResponse response){
        Cookie cookies[] = request.getCookies();
        if (cookies != null)
        {
            for (int i = 0; i < cookies.length; i++)
            {
                if (cookies[i].getName().equals(CookieUtil.COOKIE_NAME))
                {
                    Cookie cookie = new Cookie(CookieUtil.COOKIE_NAME,"");//这边得用"",不能用null
                    cookie.setPath("/");//设置成跟写入cookies一样的
                    cookie.setMaxAge(0);
                    response.addCookie(cookie);
                }
            }
        }
    }
}
